import { oauthUrl, oauthUrlYellow } from "@/services/auth";
import { Spin } from "antd";
import { useEffect, useRef, useState } from "react";
import { history, useModel } from "umi";
const { ipcRenderer } = window.require("electron");

const Auth = () => {
  const iframeRef = useRef<any>(null);
  const [loading, setLoading] = useState(false);
  const { getToken } = useModel("auth.model");
  const { isGetToken, setIsGetToken, setUserInfo } = useModel("user");
  const { EnvMode, isFullScreen } = useModel("env");

  // const listener = (event: any) => {
  //   if (event.data && event.data.indexOf(recirectUrl) != -1) {
  //     //清除监听
  //     document.body.removeEventListener("message", listener);
  //     getToken(event.data);
  //   }
  // };
  useEffect(() => {
    if (EnvMode === "YELLOW") {
      ipcRenderer.send("load-page", oauthUrlYellow, isFullScreen);
    }
    setLoading(true);
    if (isGetToken) return;
    setIsGetToken(true);
    ipcRenderer.on("login-webRequest", (event: Event, arg: string) => {
      setLoading(false);
      getToken(arg);
    });
    ipcRenderer.on("userInfo", (event: Event, userInfo: any) => {
      setLoading(false);
      setUserInfo(userInfo);
      history.push("/editor/kpi");
    });
    // document.body.removeEventListener("message", listener);
    // window.addEventListener("message", listener, false);
    // return () => {
    //   //清除监听
    //   document.body.removeEventListener("message", listener);
    // };
  }, []);
  useEffect(() => {
    if (!iframeRef.current) return;
    iframeRef.current.onload = () => {
      setLoading(false);
    };
  }, [iframeRef]);

  return (
    <div style={{ overflow: "hidden" }}>
      {loading && EnvMode !== "YELLOW" ? (
        <div
          style={{
            width: "100%",
            height: isFullScreen ? 1024 : 800,
            paddingTop: 200,
            display: "flex",
            justifyContent: "center",
          }}
        >
          <Spin />
        </div>
      ) : null}
      {EnvMode === "YELLOW" ? null : (
        <iframe
          ref={iframeRef}
          src={oauthUrl}
          width={"100%"}
          height={isFullScreen ? 1024 : 800}
        />
      )}
    </div>
  );
};

export default Auth;
